package com.imddy.gkrpc.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.imddy.gkrpc.Peer;
import com.imddy.gkrpc.common.utils.ReflectionUtils;
import com.imddy.gkrpc.transport.HttpTransportClient;
import com.imddy.gkrpc.transport.TransportClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RandomTransportSelector implements TransportSelector {
	/** 表示已经建立好链接的client */
	private List<TransportClient> clients;

	public RandomTransportSelector() {
		clients = new ArrayList<TransportClient>();
		
	}
	
	@Override
	public synchronized void init(List<Peer> peers, 
			int count, 
			Class<? extends TransportClient> clazz) {
		// TODO Auto-generated method stub
		count = Math.max(count, 1);
		for (Peer peer : peers) {
			for (int i = 0; i < count; i++) {
				TransportClient client = ReflectionUtils.newInstance(HttpTransportClient.class);
				client.connect(peer);
				clients.add(client);
			}
			log.info("connect Server");
		}
		
	}

	@Override
	public synchronized TransportClient select() {
		// TODO Auto-generated method stub
		int i = new Random().nextInt(clients.size());
		return clients.remove(i);
	}

	@Override
	public synchronized void release(TransportClient client) {
		// TODO Auto-generated method stub
		clients.add(client);
		
	}

	@Override
	public synchronized void close() {
		// TODO Auto-generated method stub
		for (TransportClient transportClient : clients) {
			transportClient.close();
		}
		clients.clear();
	}

}
